<?php

namespace Admin\Controller;

use Admin\Controller\AdminController;
use Think\Page;

class GoodsController extends AdminController {

    public function _initialize() {
        parent::_initialize();
    }

    /**
     * 商品列表页
     */
    public function index() {
    	//$url="http://ydp.mylei.cn";
        $cat = M('Cat')->select();
        $this->assign('cat', $cat);
        $name = I('name') ? I('name') : null;
        $cat_id = I('cat_id') ? I('cat_id') : null;
        if (!empty($name)) {
            $where['name'] = array("like", "%" . $name . "%");
        }
        if (!empty($cat_id)) {
            $where['cat_id'] = $cat_id;
        }
        $count = M('Goods')->where($where)->count();
        $Page = new Page($count, 8);
        setPageParameter($Page, array('name' => $name));
        $show = $Page->show();
        $list = M('Goods')->where($where)
                        ->limit($Page->firstRow . ',' . $Page->listRows)->order('goods_id desc')->select();
        foreach ($list as &$v) {
            $names = M('Cat')->where(array('cat_id' => $v['cat_id']))->find();
            $father = M('Cat')->where(array('cat_id' => $names['pid']))->find();
            $son = M('Cat')->where(array('cat_id' => $father['pid']))->find();
            $v['title'] = $names['name'] . '---' . $father['name'] . '---' . $son['name'];
            if($v['is_limit']==1){
                $v['http']="http://ydp.mylei.cn/wscjf_app/index.html#/jifenshangpingxiangqinger?goods_id=".$v['goods_id'];
            	
            }else{
                $v['http']="http://ydp.mylei.cn/wscjf_app/index.html#/jifenshangpingxiangqing?id=".$v['goods_id'];
            }
            
            //	$v['comment'] = M("Comment")->where(array('goods_id'=>$v['goods_id']))->count();
        }
        $this->assign('list', $list);
        $this->assign('search', $name);
        $this->assign('page', $show);
        if(I('type')==1){
        	$this->display('Goods/addGoodsxian');
        }else {
        	$this->display();
        }
      
    }

    /**
     * 添加商品
     */
    public function addGoods() {
    	$types=I('type');
        $goods_id = I('goods_id') ? I('goods_id') : '';
        $this->assign('goods_id', $goods_id);
        $attr_array = [];
        $last = [];
        if (!empty($goods_id)) {
            $goods = M('Goods')->where(array('goods_id' => $goods_id))->find();
            $names = M('Cat')->where(array('cat_id' => $goods['cat_id']))->find();
            $namess = M('Cat')->where(array('cat_id' => $names['pid']))->find();
            $namesss = M('Cat')->where(array('cat_id' => $namess['pid']))->find();
            $goods['cat_name'] = $namesss['name'] . "--" . $namess['name'] . '--' . $names['name'];
            $attr = M('Attr')->where(array('cat_id' => $goods['cat_id']))->select();
            foreach ($attr as &$v) {
                foreach (explode('/', $v['detail']) as &$m) {
                        $r_at = M('Goods_attr')->where(array('attr_val' => $m, 'goods_id' => $goods_id))->find();
                        if ($r_at) {
                            $attr_array[] = $r_at;
                        } else {
                            $attr_array[] = [
                                'attr_val' => $m,
                                'attr_id' => $v['attr_id'],
                                'is_price_main' => 0,
                            ];
                        }
                    }
                $v['totle'] = $attr_array;
                $attr_array = [];
            }
            $this->assign('attr', $attr);
         //   var_dump($attr);
            $goods_attr = M('Goods_attr')->where(array('goods_id' => $goods_id))->select();
            $this->assign('goods', $goods);
            $this->assign('status', 1);
        } else {
            $this->assign('status', 2);
        }
        $cat = M('Cat')->where(array('pid' => 0))->select();
        $this->assign('cat', $cat);
        if($types==1){
        	$this->display('Goods/addGoodsxian');
        }else {
        	$this->display();
        }
       
    }

    /**
     * 根据pid获取子分类
     * 
     */
    public function getCatChildByPid() {
        $pid = I('pid');
        if ($pid == 0) {
            $this->ajaxReturn([]);
        }
        $cat = M('Cat')->where(array('pid' => $pid))->select();
        $this->ajaxReturn($cat);
    }

    /**
     * 根据分类获取属性
     */
    public function getAttr() {
        $cat_id = I('cat_id') ? I('cat_id') : null;
        $attr = M('Attr')->where(array('cat_id' => $cat_id))->select();
        foreach ($attr as &$v) {
            $v['attr'] = explode("/", $v['detail']);
          //  var_dump($attr);
        }
      //  var_dump($attr);exit();
        $this->ajaxReturn($attr);
    }
   

    /**
     * 添加商品执行方法
     */
    public function doAddGoods() {
    	//dump($_POST);die;
        $goods_id = I('goods_id') ? I('goods_id') : '';
        $cat = I('cat_child') ? I('cat_child') : I('cat_child1');
        $is_limit=I('is_limit');
        $postage = intval(I('postage')); 
        $goods_price = I('goods_price');
        $zhuli_price = I('zhuli_price');
        $goods_old_price = I('old_price');
        $content = I('content') ? I('content') : '';
        $content_all = I('content_all') ? $_POST['content_all'] : '';
        $is_yilai = I('yilai') ? I('yilai') : '';
        $name = I('name') ? I('name') : '';
        $rule = I('rule')?$_POST['rule'] : '';
        $start_time = I('startTime') ? strtotime(I('startTime')) : '';
        $end_time = I('endTime') ? strtotime(I('endTime')) : '';
        $pqnews=I('pqnews')?$_POST['pqnews']:'';
        $time=$end_time-$start_time;
        if (empty($_FILES['image']['name']) && empty($goods_id)) {
        	$this->error('请上传图片');
        }
        if (empty($name)) {
        	$this->error('请输入商品名称');
        }
        if (empty($content)) {
        	$this->error('请输入商品的短描述');
        }
        if (empty($content_all)) {
        	$this->error('请输入商品的详情描述');
        }
        if($is_limit==1){
        	if(empty($goods_price)){
        		$this->error('请输入拼抢商品价格');
        	}
        	if(empty($goods_old_price)){
        		$this->error('请输入商品原价格');
        	}
        	if(empty($rule)){
        		$this->error('请输入活动信息');
        	}
        	if(empty($zhuli_price)){
        		$this->error('请输入助力价格');
        	}
        	 if($time<0){
        		$this->error('您的结束时间必须大于开始时间');
        	}
        	if($pqnews==''){
        		$this->error('请添加拼抢规则');
        	}
        	
        }else{
        	if (empty($cat)) {
        		$this->error('请选择分类');
        	}
        	if(empty($is_yilai)){
        		$this->error('请选择价格推荐');
        	}
        }   
        if (!empty($_FILES['image'])) {
            $image = $this->imgUpload($_FILES['image']);
        }
       
        if (empty($goods_id)) {
            $goods = [
                'name' => $name,
                'cat_id' => $cat,
                'image' => $image,
                'is_sale' => 1,
                'content' => $content,
                'content_all' => $content_all,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'postage'=>$postage,
                'goods_price'=>$goods_price,
                'is_limit'=>$is_limit,
                'rule'=>$rule,
                'old_price'=>$goods_old_price,
                'pqnews'=>$pqnews,
                'zhuli_price'=>$zhuli_price,
            ];
            $goods_id = M('Goods')->add($goods);
            $data = [];
            $attr = M('Attr')->where(array('cat_id' => $cat))->select();
            foreach ($attr as &$v) {
                $attrs = explode('/', $v['detail']);
                foreach ($attrs as $m) {
                    if ($_POST[$m . '_kucun']) {
                        if ($is_yilai == $m) {
                            $is_price_main = 1;
                        } else {
                            $is_price_main = 0;
                        }
                        $data = [
                            'attr_id' => $v['attr_id'],
                            'attr_val' => $m,
                            'attr_kucun' => $_POST[$m . '_kucun'],
                            'price' => $_POST[$m . '_jiage'],
                            'fanjifen' => $_POST[$m . '_fanjifen'],
                            'goods_id' => $goods_id,
                            'is_price_main' => $is_price_main,
                            
                        ];
                        if ($_POST[$m . '_jifen'] > 0 && $_POST[$m . '_jifen']) {
                            $data['jifen'] = $_POST[$m . '_jifen'];
                        } else {
                            $data['jifen'] = null;
                        }
                        if ($_POST[$m . '_jiage'] > 0 && $_POST[$m . '_jiage']) {
                            $data['price'] = $_POST[$m . '_jiage'];
                        } else {
                            $data['price'] = null;
                        }

                        $r_attr_main[] = M('Goods_attr')->add($data);
                    }
                }
            }
            $this->success('添加成功', U('Goods/index'));
        } else {            
            if (!$image) {
                $goods = [
                    'name' => $name,
                    'is_sale' => 1,
                    'content' => $content,
                    'content_all' => $content_all,
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'postage'=> $postage,
                    'goods_price'=>$goods_price,
                    'is_limit'=>I('is_limit'),
                    'old_price'=>$goods_old_price,
                    'pqnews'=>$pqnews,
                    'rule'=>$rule,
                    'zhuli_price'=>$zhuli_price,
                ];
            } else {
                $goods = [
                    'name' => $name,
                    'image' => $image,
                    'is_sale' => 1,
                    'content' => $content,
                    'content_all' => $content_all,
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'postage'=> $postage,
                    'goods_price'=>$goods_price,
                    'is_limit'=>I('is_limit'),
                    'old_price'=>$goods_old_price,
                    'pqnews'=>$pqnews,
                    'rule'=>$rule,
                    'zhuli_price'=>$zhuli_price,
                ];
            }
            $r_goods = M('Goods')->where(array('goods_id' => $goods_id))->save($goods);
            //var_dump($r_goods);die;
            $attr = M('Attr')->where(array('cat_id' => $cat))->select();
           // var_dump($attr);exit();
            foreach ($attr as &$v) {
                $attrs = explode('/', $v['detail']);
                foreach ($attrs as $m) {
                    if ($_POST[$m . '_kucun']) {
                        if ($is_yilai == $m) {
                            $is_price_main = 1;
                        } else {
                            $is_price_main = 0;
                        }
                        if (M('Goods_attr')->where(array('attr_id' => $v['attr_id'], 'attr_val' => $m, 'goods_id' => $goods_id))->find()) {
                            //dump($m.'_jifen');
                            $data = [
                                'attr_id' => $v['attr_id'],
                                'attr_val' => $m,
                                'attr_kucun' => $_POST[$m . '_kucun'],
                                'price' => $_POST[$m . '_jiage'],
                                'fanjifen' => $_POST[$m . '_fanjifen'],
                                'goods_id' => $goods_id,
                                'is_price_main' => $is_price_main,
                                
                            ];
                            if ($_POST[$m . '_jifen'] > 0 && $_POST[$m . '_jifen']) {
                                $data['jifen'] = $_POST[$m . '_jifen'];
                            } else {
                                $data['jifen'] = null;
                            }
                            $r_attr_main[] = M('Goods_attr')->where(array('attr_id' => $v['attr_id'], 'attr_val' => $m, 'goods_id' => $goods_id))->save($data);
                        } else {
                            $data = [
                                'attr_id' => $v['attr_id'],
                                'attr_val' => $m,
                                'attr_kucun' => $_POST[$m . '_kucun'],
                                'price' => $_POST[$m . '_jiage'],
                                'fanjifen' => $_POST[$m . '_fanjifen'],
                                'goods_id' => $goods_id,
                                'is_price_main' => $is_price_main,
                                'pqnews'=>$pqnews,
                                'rule'=>$rule,
                            ];
                            if ($_POST[$m . '_jifen'] > 0 && $_POST[$m . '_jifen']) {
                                $data['jifen'] = $_POST[$m . '_jifen'];
                            } else {
                                $data['jifen'] = null;
                            }
                            if ($_POST[$m . '_jiage'] > 0 && $_POST[$m . '_jiage']) {
                                $data['price'] = $_POST[$m . '_jiage'];
                            } else {
                                $data['price'] = null;
                            }
                            $r_attr_main[] = M('Goods_attr')->add($data);
                        }
                    } else {
                        M('Goods_attr')->where(array('attr_id' => $v['attr_id'], 'attr_val' => $m, 'goods_id' => $goods_id))->delete();
                    }
                }
            }
            $this->success('修改成功');
        }
    }
    /**
     * 分类列表
     */
    public function cat() {
        $count = M('Cat')->where(array('pid' => 0))->count();
        $Page = new Page($count, 20);
        //setPageParameter($Page, array('account'=>$account));
        $show = $Page->show();
        $list = M('Cat')
                        ->order("add_time")
                        ->where(array('pid' => 0))
                        ->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($list as &$v) {
            $v['child'] = M('Cat')->where(array('pid' => $v['cat_id']))->select();
            foreach ($v['child'] as &$vv) {
                $vv['child'] = M('Cat')->where(array('pid' => $vv['cat_id']))->select();
            }
        }
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 添加分类
     */
    public function addCat() {
        $cat_id = I('cat_id') ? I('cat_id') : null;
        $pid = I('pid');
        $cat = M('Cat')->where(array('cat_id' => $cat_id))->find();
        $this->assign('list', $cat);
        $this->assign('pid', $pid);
        $this->display();
    }

    /**
     * 添加分类
     */
    public function doAddCat() {
        $pid = I('pid');
        if (empty($pid)) {
            $pid = 0;
        }
        $cat_id = I('cat_id') ? I('cat_id') : null;
        $name = I('name');
        if (empty($cat_id)) {
            if (empty($name)) {
                $this->error('请输入名称');
            }
            $cat = [
                'name' => $name,
                'add_time' => time(),
                'pid' => $pid,
            ];
            $r = M('Cat')->add($cat);
            $this->success('操作成功', U('Goods/cat'));
        } else {
            $cat = [
                'name' => $name,
            ];
            $r = M('Cat')->where(array('cat_id' => $cat_id))->save($cat);
            $this->success('操作成功', U('Goods/cat'));
        }
    }

    /**
     * 删除分类
     */
    public function del() {
        $cat_id = I('cat_id');
        $pid = M("Cat")->where(['cat_id' => $cat_id])->find();
        $r = M('Cat')->delete($cat_id);
        $this->success('操作成功', U('Goods/cat'));
    }

    public function delGoods() {
        $cat_id = I('goods_id');
        $r = M('Goods')->delete($cat_id);
        $this->success('操作成功');
    }

    /**
     * 添加属性
     */
    public function addAttr() {
        $cat_id = I('cat_id');
        $this->assign('cat_id', $cat_id);
        $attr_id = I('attr_id') ? I('attr_id') : null;
        $attr = M('Attr')->where(array('attr_id' => $attr_id))->find();
        $this->assign('list', $attr);
        $this->display();
    }

    /**
     * 查看当前分类的属性列表
     */
    public function showAttr() {
        $cat_id = I('cat_id') ? I('cat_id') : null;
        $this->assign('cat_id', $cat_id);
        $attr = M('Attr')->where(array('cat_id' => $cat_id))->select();
        $this->assign('list', $attr);
        $this->display();
    }

    /**
     * 添加属性方法
     */
    public function doAddAttr() {
        $attr_id = I('attr_id') ? I('attr_id') : null;
        $cat_id = I('cat_id') ? I('cat_id') : null;
        $name = I('name') ? I('name') : null;
        $detail = I('detail') ? I('detail') : null;
        if (empty($attr_id)) {
            if (empty($name)) {
                $this->error('请输入名称');
            }
            if (empty($detail)) {
                $this->error('请输入属性详情，以英文逗号隔开');
            }
            $attr = [
                'name' => $name,
                'cat_id' => $cat_id,
                'detail' => $detail,
            ];
            $r = M('Attr')->add($attr);
            $this->success('操作成功', U('Goods/showAttr', array('cat_id' => $cat_id)));
        } else {
            $attr = [
                'name' => $name,
                'detail' => $detail,
            ];
            $r = M('Attr')->where(array('attr_id' => $attr_id))->save($attr);
            $this->success('操作成功', U('Goods/showAttr', array('cat_id' => $cat_id)));
        }
    }

    public function setYilai() {
        $attr_id = I('attr_id') ? I('attr_id') : null;
        $cat_id = I('cat_id') ? I('cat_id') : null;
        $r = M('Attr')->where(array('attr_id' => $attr_id))->setField('is_yilai', 1);
        $where['attr_id'] = array('neq', $attr_id);
        $where['cat_id'] = $cat_id;
        $r_cancel = M('Attr')->where($where)->setField('is_yilai', 0);
        $this->success('操作成功', U('Goods/showAttr', array('cat_id' => $cat_id)));
    }

    /**
     * 删除属性
     */
    public function delAttr() {
        $attr_id = I('attr_id') ? I('attr_id') : null;
        $cat_id = I('cat_id') ? I('cat_id') : null;
        $r = M('Attr')->delete($attr_id);
        $this->success('操作成功', U('Goods/showAttr', array('cat_id' => $cat_id)));
    }

    public function images() {
        $goods_id = I('goods_id') ? I('goods_id') : null;
        $pics = M('Goods_pic')->where(array('goods_id' => $goods_id))->select();
        $this->assign('pics', $pics);
        $goods = M('Goods')->where(array('goods_id' => $goods_id))->find();
        session('goods_id', $goods_id);
        $this->assign('goods_id', $goods_id);
        $this->assign('goods', $goods);
        $this->display();
    }

    public function getImages() {
        $url = $this->imgUpload($_FILES['file']);
        $data = [
            'goods_id' => session('goods_id'),
            'pic' => $url,
            'add_time' => time(),
        ];
        M('Goods_pic')->add($data);
        //M('goods')->add(['pics'=>$_FILES['file']['name']]);
        //dump($_FILES);die;
    }

    public function deletePic() {
        $goods_pic_id = I('goods_pic_id');
        $goods_id = I('goods_id');
        $pic = M('Goods_pic')->where(array('goods_pic_id' => $goods_pic_id))->find();
        //dump('.'.$pic['pic']);
        $s = unlink('.' . $pic['pic']);
        //dump($s);die;
        $r = M('Goods_pic')->delete($goods_pic_id);
        $this->success('删除成功', U('Goods/images', array('goods_id' => $goods_id)));
    }

    public function tuijian() {
        $goods_id = I('goods_id') ? I('goods_id') : null;
        $is_tuijian = M('Goods')->where('goods_id =' . $goods_id)->find()['is_tuijian'];
        if ($is_tuijian == 1) {
            $tuijian = 0;
        }
        if ($is_tuijian == 0) {
            $tuijian = 1;
        }
        $re = M('Goods')->where('goods_id =' . $goods_id)->save(array('is_tuijian' => $tuijian));
        if ($re) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    public function toComment() {
        $goods_id = I('goods_id');
        $list = M("Comment c")->join("yang_member m ON m.openid=c.open_id")
                        ->where(array('goods_id' => $goods_id))->select();
        $this->assign('list', $list);
        $this->display();
    }

    public function delComment() {
        $id = I('id');
        $re = M("Comment")->where(array("cid" => $id))->delete();
        if ($re) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    //下架商品
    public function setSale() {
        $goods_id = I('goods_id');
        $r = M("Goods")->where(array('goods_id' => $goods_id))->find();
        if ($r['is_sale'] == 1) {
            $is_sale = 0;
        }
        if ($r['is_sale'] == 0) {
            $is_sale = 1;
        }
        $re = M("Goods")->where(array("goods_id" => $goods_id))->save(array("is_sale" => $is_sale));
        if ($re) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    //设置月销量
    public function setSaleCount() {
        $goods_id = I('id');
        $num = I('num');
        $year = date('y', time());
        $mouth = date('m', time());
        $count = M('count_month')->where(['goods_id' => $goods_id, 'year' => $year, 'month' => $mouth])->find();
        $data['count'] = $num;
        if ($count) {
            //存在数据就修改否则就新增
            $re = M('count_month')->where(['goods_id' => $goods_id, 'year' => $year, 'month' => $mouth])->save($data);
        } else {
            $re = M('count_month')->add(['goods_id' => $goods_id, 'year' => $year, 'month' => $mouth, 'count' => $num]);
        }
        if ($re) {
            $this->ajaxReturn(['status' => 1]);
        } else {
            $this->ajaxReturn(['status' => -1]);
        }
    }

    public function setTime() {
        $goods_id = I('goods_id');
        if (IS_POST) {
            $data['start_time'] = strtotime($_POST['start_datetime']);
            $data['end_time'] = strtotime($_POST['end_datetime']);
            $id = $_POST['goods_id'];
            $list = M('goods')->where(array('goods_id' => $id))->save($data);
//            M('')->where('')->getField('user','12312');
            if ($list) {
                $this->success('设置成功', U('Goods/index'));
            } else {
                $this->error('设置失败', U('Goods/index'));
            }
        }
        $this->assign('goods_id', $goods_id);
        $this->display('set_time');
    }

    public function setRule(){
        $id = I('id');
        $list = M('rob_rule')->where(array('id'=>1))->find();
        if(IS_POST){
            $data['title'] = I('title');
            $data['content'] = I('content');
           
            if(!empty($list)){
                $result = M('rob_rule')->where(array('id'=>1))->save($data);
            }else{
                $result = M('rob_rule')->add($data);
            }
            
            if ($result) {
                $this->success('设置成功', U('Goods/index'));
            } else {
                $this->error('设置失败', U('Goods/index'));
            }
        }
        $this->assign('id',$id);
        $this->assign('list',$list);
        $this->display('setRule');
    }
}
